package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //检查一下用户是否登录，如果已经登录，就放行，如果没有登录就拦截让他去登录
        //将request和respond进行类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //进入先处理特殊情况将【登录、注册相关资源】和【静态资源】直接放行
        //情况一：将【登录、注册相关资源】和【静态资源】直接放行
            //1.在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp", "/register.jsp", "/css","/images","/js", "/login", "/user", "/verifyCode","/SelectByPageServlet"};
        //2.获取当前访问的资源路径
        String uri = req.getRequestURI();
        //3.遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {
            //4.判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
            /*
            比如当前访问的资源路径是 /brand-demo/login.jsp
            而字符串 /brand-demo/login.jsp 包含了字符串 /login.jsp ，所以就需要放行
            */
            if (uri.contains(u)) {
                //找到了，放行
                chain.doFilter(req, resp);
                //不再继续向下走了,这里要return
                return;
            }
        }


        //检查session是否存放了login_user
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("LOGIN_USER");
        //2. 判断user是否为null
        if(user != null){
            // 已经登录,放行
            chain.doFilter(req, resp);
        }else {
            // 没有登陆，存储提示信息，跳转到登录页面
            req.setAttribute("LOGIN_MSG","您尚未登陆！");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
        return;
    }
}
